package cn.turboinfo.fuyang.api.domain.mini.usecase.shop;

import cn.turboinfo.fuyang.api.domain.common.service.category.CategoryService;
import cn.turboinfo.fuyang.api.domain.common.service.product.ProductService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.common.pojo.category.Category;
import cn.turboinfo.fuyang.api.entity.common.pojo.product.Product;
import com.google.common.collect.Lists;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 查看门店服务类别
 *
 * @author gadzs
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class MiniListCategoryByShopUseCase extends AbstractUseCase<MiniListCategoryByShopUseCase.InputData, MiniListCategoryByShopUseCase.OutputData> {

    private final ProductService productService;
    private final CategoryService categoryService;

    @Override
    protected OutputData doAction(InputData inputData) {
        val shopId = inputData.getId();

        Map<Long, Long> productMap = productService.findByShopIdCollection(Lists.newArrayList(shopId)).stream().collect(Collectors.groupingBy(Product::getCategoryId, Collectors.counting()));

        val categoryList = categoryService.findByIdCollection(productMap.keySet());
        List<CategoryData> categoryDataList = categoryList.stream().map(
                category -> {
                    return CategoryData.builder().category(category).sortValue(productMap.get(category.getId())).build();
                }
        ).collect(Collectors.toList());
        categoryDataList = categoryDataList.stream().sorted(Comparator.comparing(CategoryData::getSortValue)).collect(Collectors.toList());
        return OutputData.builder()
                .categoryList(categoryDataList)
                .build();
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputData extends AbstractUseCase.InputData {

        /**
         * 门店id
         */
        @NotNull(
                message = "公司id不能为空"
        )
        private Long id;

        /**
         * 公司id
         */
        private Long companyId;

    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {

        private List<CategoryData> categoryList;
    }


    @Getter
    @Setter
    @Builder
    public static class CategoryData {

        private Category category;
        private Long sortValue;
    }
}
